import React, { useEffect, useState } from 'react';
import {
  Tree,
  Table,
  Space,
  Button,
  message,
  Card,
  Row,
  Col,
  Modal,
  Form,
  Input,
  Select,
  TreeSelect,
  Transfer,
  Tooltip,
  Popconfirm,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import { OrganizationItem, UserItem, RoleItem } from 'admin/schema/Cas';
import {
  getCasOrganizationsShow,
  getCasUsers,
  addCasUser,
  updateCasUser,
  getCasRoles,
  updateCasUserRole,
  resetCasUserPassword,
  deleteCasUser,
} from 'admin/servers/modules/Cas';
import { validateUserPwdRule } from 'utils/modules/validateUserPwdRule';
import { convertToTree } from '../utils';
import { verifyPhone } from 'utils/tools';
import { debounce, isEmpty } from 'lodash';

interface UserFormValues {
  username: string;
  password?: string;
  nickname: string;
  phone: string;
  email: string;
  status: number;
  orgId: string;
}

interface ResetPasswordFormValues {
  password: string;
  confirmPassword: string;
}

const Users: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [orgTree, setOrgTree] = useState<DataNode[]>([]);
  const [selectedOrgId, setSelectedOrgId] = useState<string>('');
  const [users, setUsers] = useState<UserItem[]>([]);
  const [roles, setRoles] = useState<RoleItem[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增用户');
  const [form] = Form.useForm<UserFormValues>();
  const [editingUser, setEditingUser] = useState<UserItem | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [currentUserId, setCurrentUserId] = useState<string>('');
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
  const [resetPasswordModalVisible, setResetPasswordModalVisible] = useState(false);
  const [resetPasswordUserId, setResetPasswordUserId] = useState<string>('');
  const [resetPasswordForm] = Form.useForm<ResetPasswordFormValues>();
  const [searchForm] = Form.useForm();

  // 获取单位树
  const fetchOrgTree = async () => {
    try {
      const response = await getCasOrganizationsShow();
      if (response.status === 200) {
        const transformToTreeData = (items: OrganizationItem[]): DataNode[] => {
          return items.map(item => ({
            title: item.name,
            key: item.id,
            children: item.children ? transformToTreeData(item.children) : undefined,
          }));
        };
        const treeData = transformToTreeData(convertToTree(response.data));
        setOrgTree(treeData);

        // 默认选中第一个单位
        if (treeData.length > 0) {
          const firstOrgId = treeData[0].key as string;
          setSelectedOrgId(firstOrgId);
          fetchUsers(firstOrgId, 1, 10, {});
        }
      }
    } catch (error) {
      console.error('获取单位树出错:', error);
    }
  };

  // 获取用户列表
  const fetchUsers = async (orgId: string, page: number, pageSize: number, params: any) => {
    setLoading(true);
    try {
      const response = await getCasUsers(page - 1, pageSize, {
        orgId,
        username: params.username || undefined,
        phone: params.phone || undefined,
        status: params.status,
      });
      if (response.status === 200) {
        const { content, totalElements, number } = response.data;
        setUsers(content);
        setPagination(prev => ({
          ...prev,
          current: number + 1,
          pageSize,
          total: totalElements,
        }));
      }
    } catch (error) {
      console.error('获取用户列表出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      const response = await getCasRoles();
      if (response.status === 200) {
        setRoles(response.data);
      }
    } catch (error) {
      console.error('获取角色列表出错:', error);
    }
  };

  useEffect(() => {
    fetchOrgTree();
    fetchRoles();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleOrgSelect = (
    selectedKeys: React.Key[],
    info: {
      selected: boolean;
      selectedNodes: DataNode[];
      node: DataNode;
      event: 'select';
    }
  ) => {
    if (isEmpty(selectedKeys)) {
      return;
    }
    const orgId = selectedKeys[0] as string;
    setSelectedOrgId(orgId);
    fetchUsers(orgId, 1, 10, {});
    searchForm.resetFields();
  };

  const handleTableChange = (pagination: any) => {
    fetchUsers(selectedOrgId, pagination.current, pagination.pageSize, searchForm.getFieldsValue());
  };

  const handleAdd = () => {
    setModalTitle('新增用户');
    setEditingUser(null);
    form.resetFields();
    form.setFieldsValue({ orgId: selectedOrgId, status: 1 });
    setModalVisible(true);
  };

  const handleEdit = (record: UserItem) => {
    setModalTitle('编辑用户');
    setEditingUser(record);
    form.setFieldsValue({
      username: record.username,
      nickname: record.nickname,
      phone: record.phone,
      email: record.email,
      status: record.status,
      orgId: record.orgId,
    });
    setModalVisible(true);
  };

  const handleModalOk = debounce(async () => {
    try {
      const values = await form.validateFields();
      if (editingUser) {
        // 更新用户
        const response = await updateCasUser({
          id: editingUser.id,
          username: values.username,
          nickname: values.nickname,
          phone: values.phone,
          email: values.email,
          status: values.status,
          orgId: values.orgId,
          roleIds: '', // 保持空字符串，角色通过单独的接口更新
        });

        if (response.status === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchUsers(
            selectedOrgId,
            pagination.current,
            pagination.pageSize,
            searchForm.getFieldsValue()
          );
        }
      } else {
        // 新增用户
        const response = await addCasUser({
          username: values.username,
          password: values.password,
          nickname: values.nickname,
          phone: values.phone,
          email: values.email,
          status: values.status,
          orgId: values.orgId,
          roleIds: '', // 保持空字符串，角色通过单独的接口更新
        });

        if (response.status === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchUsers(
            selectedOrgId,
            pagination.current,
            pagination.pageSize,
            searchForm.getFieldsValue()
          );
        }
      }
    } catch (error) {
      console.error('表单验证或提交出错:', error);
    }
  }, 500);

  const handleModalCancel = () => {
    setModalVisible(false);
  };

  // 处理角色分配
  const handleRoleAssign = (record: UserItem) => {
    setCurrentUserId(record.id);
    setSelectedRoles(record.roles?.map(role => role.id) || []);
    setRoleModalVisible(true);
  };

  // 处理角色分配确认
  const handleRoleModalOk = debounce(async () => {
    try {
      const response = await updateCasUserRole({
        id: currentUserId,
        roleIds: selectedRoles.join(','),
      });

      if (response.status === 200) {
        message.success('角色分配成功');
        setRoleModalVisible(false);
        fetchUsers(
          selectedOrgId,
          pagination.current,
          pagination.pageSize,
          searchForm.getFieldsValue()
        );
      }
    } catch (error) {
      console.error('角色分配出错:', error);
    }
  }, 500);

  // 处理重置密码
  const handleResetPassword = (record: UserItem) => {
    setResetPasswordUserId(record.id);
    resetPasswordForm.resetFields();
    setResetPasswordModalVisible(true);
  };

  // 处理重置密码确认
  const handleResetPasswordOk = debounce(async () => {
    try {
      const values = await resetPasswordForm.validateFields();
      const response = await resetCasUserPassword({
        id: resetPasswordUserId,
        password: values.password,
        confirmPassword: values.confirmPassword,
      });

      if (response.status === 200) {
        message.success('密码重置成功');
        setResetPasswordModalVisible(false);
      }
    } catch (error) {
      console.error('密码重置出错:', error);
    }
  }, 500);

  const handleDelete = async (id: string) => {
    try {
      const response = await deleteCasUser(id);
      if (response.status === 200) {
        message.success('删除成功');
        fetchUsers(
          selectedOrgId,
          pagination.current,
          pagination.pageSize,
          searchForm.getFieldsValue()
        );
      }
    } catch (error) {
      console.error('删除出错:', error);
    }
  };

  const columns: ColumnsType<UserItem> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: '180px',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width: '180px',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: '130px',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: '130px',
    },
    {
      title: '所属单位',
      dataIndex: 'orgName',
      key: 'orgName',
      width: '180px',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '60px',
      render: status => (status === 1 ? '启用' : '禁用'),
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '180px',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: '260px',
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" style={{ paddingInline: 0 }} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" style={{ paddingInline: 0 }} onClick={() => handleRoleAssign(record)}>
            分配角色
          </Button>
          <Button
            type="link"
            style={{ paddingInline: 0 }}
            onClick={() => handleResetPassword(record)}
          >
            重置密码
          </Button>
          <Popconfirm
            title="确定要删除此该用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger style={{ paddingInline: 0 }}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 密码验证规则
  const validatePassword = (_: any, value: string) => {
    const Fn = validateUserPwdRule;
    const { code, msg } = Fn.checkPassword(null, value);
    return code ? Promise.reject(msg) : Promise.resolve();
  };

  const handleReset = debounce(() => {
    searchForm.resetFields();
    fetchUsers(selectedOrgId, 1, 10, {});
  }, 500);

  const handleFinish = debounce((values: any) => {
    fetchUsers(selectedOrgId, 1, 10, values);
  }, 500);

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={16}>
        <Col span={6}>
          <Card title="单位" bordered={false}>
            <Tree
              treeData={orgTree}
              selectedKeys={[selectedOrgId]}
              onSelect={handleOrgSelect}
              defaultExpandAll
            />
          </Card>
        </Col>
        <Col span={18}>
          <Card
            title="用户列表"
            bordered={false}
            extra={
              <Button type="primary" onClick={handleAdd}>
                新增用户
              </Button>
            }
          >
            <Form
              layout="inline"
              form={searchForm}
              onFinish={handleFinish}
              style={{ marginBottom: '20px' }}
            >
              <Form.Item label="用户名" name="username">
                <Input placeholder="请输入用户名" />
              </Form.Item>
              <Form.Item label="手机号" name="phone">
                <Input placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item label="状态" name="status">
                <Select placeholder="请选择状态" allowClear>
                  <Select.Option value={1}>启用</Select.Option>
                  <Select.Option value={0}>禁用</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                  重置
                </Button>
              </Form.Item>
            </Form>
            <Table
              columns={columns}
              dataSource={users}
              rowKey="id"
              loading={loading}
              pagination={{
                ...pagination,
                showTotal: (total: number) => `共 ${total} 条`,
                showSizeChanger: true,
              }}
              scroll={{ x: 1300 }}
              onChange={handleTableChange}
            />
          </Card>
        </Col>
      </Row>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        destroyOnClose
        maskClosable={false}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  ...(editingUser
                    ? []
                    : [
                        { max: 60, message: '最大长度为60位字符' },
                        { min: 6, message: '最小长度为6位字符' },
                        {
                          pattern: /^[a-zA-Z][a-zA-Z]+$/,
                          message: '用户名必须为英文',
                        },
                      ]),
                ]}
              >
                <Input disabled={!!editingUser} placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="phone" label="手机号" rules={verifyPhone}>
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>

          {!editingUser && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="password"
                  label="密码"
                  tooltip="8位以上字符，需包含大写字母、小写字母、数字和特殊字符中的三类"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { max: 60, message: '最大长度为60位字符' },
                    { validator: validatePassword },
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="confirmPassword"
                  label="确认密码"
                  dependencies={['password']}
                  rules={[
                    { required: true, message: '请确认密码' },
                    { max: 60, message: '最大长度为60位字符' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject('两次输入的密码不一致');
                      },
                    }),
                  ]}
                >
                  <Input.Password placeholder="请再次输入密码" />
                </Form.Item>
              </Col>
            </Row>
          )}

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[{ max: 60, message: '最大长度为60位字符' }]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[{ max: 60, message: '最大长度为60位字符' }]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="orgId" label="所属单位">
                <TreeSelect
                  placeholder="请选择所属单位"
                  disabled={!!editingUser}
                  treeData={orgTree}
                  treeDefaultExpandAll
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="状态" initialValue={1}>
                <Select>
                  <Select.Option value={1}>启用</Select.Option>
                  <Select.Option value={0}>禁用</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title="分配角色"
        visible={roleModalVisible}
        onOk={handleRoleModalOk}
        onCancel={() => setRoleModalVisible(false)}
        maskClosable={false}
        destroyOnClose
        width={800}
      >
        <Transfer
          dataSource={roles.map(role => ({
            key: role.id,
            title: role.name,
            description: role.description || '',
          }))}
          titles={['可选角色', '已选角色']}
          targetKeys={selectedRoles}
          onChange={targetKeys => setSelectedRoles(targetKeys as string[])}
          render={item => (
            <Tooltip title={item.description} placement="right">
              {item.title}
            </Tooltip>
          )}
          listStyle={{
            width: 400,
            height: 400,
          }}
        />
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        visible={resetPasswordModalVisible}
        onOk={handleResetPasswordOk}
        onCancel={() => setResetPasswordModalVisible(false)}
        maskClosable={false}
        destroyOnClose
      >
        <Form form={resetPasswordForm} layout="vertical">
          <Form.Item
            name="password"
            label="新密码"
            tooltip="8位以上字符，需包含大写字母、小写字母、数字和特殊字符中的三类"
            rules={[
              { required: true, message: '请输入密码' },
              { max: 60, message: '最大长度为60位字符' },
              { validator: validatePassword },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认新密码' },
              { max: 60, message: '最大长度为60位字符' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次输入的密码不一致');
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Users;
